const express = require("express");
const url = require("url");

const {findgoodslist,searchgoodsbyname} = require("../../module/handlegoods");

const router = new express.Router();

router.get("/",(request,response)=>{
    let query = url.parse(request.url,true).query;
    let page = Number(query.page)||1;
    let count = Number(query.count)||10;
    let search = query.search;
    if(typeof(search) == "undefined"){
        findgoodslist(page,count)
        .then(
            ({result,pages})=>{
                let arr = [];
                for(let i=1;i<=pages;i++){
                    arr.push(i);
                }
                response.render("buyer/index",{
                    islogin: false,
                    goodsactive: "active",
                    result,
                    page,
                    arr,
                    count
                })
            },
            (msg)=>{
                response.json({
                    message: msg
                })
            }
        )
    }else if(search){
        searchgoodsbyname(page,count,search)
        .then(
            ({result,pages})=>{
                let arr = [];
                for(let i=1;i<=pages;i++){
                    arr.push(i);
                }
                response.render("buyer/indexsearch",{
                    islogin: false,
                    goodsactive: "active",
                    result,
                    page,
                    arr,
                    count,
                    search
                })
            },
            (msg)=>{
                response.json({
                    message: msg
                })
            }
        )
    }
})

router.get("/sellerlist",(request,response)=>{
    response.render("buyer/sellerlist",{
        islogin: false,
        sellerlistactive: "active"
    })
})

module.exports = router;